var $dataInfo = $('#labelNumTable');//统计表

//防止表头与表格不对齐
$(window).resize(function () {
    $dataInfo.bootstrapTable('resetView');
});

$(function () {
    initLabelNumTable();//初始化统计表
    polyLineInitData();//折线图数据初始化
    minutePieInitData();//饼状图数据初始化
    
})

//折线图数据初始化
function polyLineInitData(){
    $.ajax({
        url: "http://localhost:8087/call/getPolyLineByAnswers",
        async: true,
        data: queryParams(),
        type: "POST",
        dataType: "json",
        success: function (result) {
            if(result.code == "000000"){
                polyLineInit('polyLine',result.data);//折线图
            }
        },
        error: function (res){
            alert('请求失败')
        }
    })
}

//饼状图数据初始化
function minutePieInitData() {
    $.ajax({
        url: "http://localhost:8087/call/getMinutePieData",
        async: true,
        data: queryParams(),
        type: "POST",
        dataType: "json",
        success: function (result) {
            if(result.code == "000000"){
                // var newArr = result.data.map(item => ({
                //     name: item.productName,
                //     value: item.proportion,
                // }))
                // pieInit('minutePie','通话时长',result.data)//饼状图
                for (var i = 0; i < result.data.length; i++) {
                    var value = result.data[i].value;
                    var comparedToLastMonth = result.data[i].comparedToLastMonth;
                    switch (result.data[i].name) {
                        case '30秒':
                            $('#CallTime30').html(value || '0');
                            //$('#percentage30').text(comparedToLastMonth);
                            break;
                        case '60秒':
                            $('#CallTime60').html(value || '0');
                            //$('#percentage60').text(comparedToLastMonth);
                            break;
                        case '90秒':
                            $('#CallTime90').html(value || '0');
                            //$('#percentage90').text(comparedToLastMonth);
                            break;
                        case '大于90秒':
                            $('#CallTimeMore').html(value || '0');
                            //$('#percentageMore').text(comparedToLastMonth);
                            break;
                    }
                }
                $('#CallTime30')
            }
        },
        error: function (res){
            alert('请求失败')
        }
    })
}

function initLabelNumTable() {
    //先销毁表格
    $dataInfo.bootstrapTable('destroy');
    $dataInfo.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: 'https://mgapi.dcrm.cn/call/selectCallOutPage',//请求地址
        //url: 'http://127.0.0.1:8087/call/selectCallOutPage',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: false,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'tatolHour',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'formId',
        idField: 'formId',
        pageSize: 50,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: "[50,100]",//可供选择的每页的行数
        queryParams: queryParamsTable,//查询参数
        columns: [
            {title: '主键', field: 'formId', visible: false},
            {title: '姓名', field: 'userName', align: 'left', valign: 'middle'},
            {title: '电话数量', field: 'tatolNumber', align: 'left', valign: 'middle'},
            {title: '60s以内', field: 'inSixSeconds', align: 'left', valign: 'middle'},
            {title: '60-90s', field: 'sixToNineSeconds', align: 'left', valign: 'middle'},
            {title: '60s以上', field: 'onSixSeconds', align: 'left', valign: 'middle'},
            {title: '90s以上', field: 'onNineSeconds', align: 'left', valign: 'middle'},
            {title: '总时长', field: 'tatolHour', align: 'left', valign: 'middle'}, //,sortable: true
            {title: '外出拜访量', field: 'bfCount', align: 'left', valign: 'middle'}, //,sortable: true
        ],
        responseHandler: function (result) {
            // if (result.code == "000000"){
            //     var obj = {
            //         "rows": result.data,
            //         "total": result.totalRecords
            //     };
            // } else {
            //     var obj = {
            //         "total": 0,
            //         "rows": [],
            //     }
            // }
            var obj = {
                "rows": result.list,

                "total": result.totalRecords,
            };
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    })
}

//拼接百分号
function splicingPercentSigns(value, row, index){
    return '<span> '+ value +'% </span>';
}

function timeSelect(th,type) {
    $(th).addClass('active-second')
    $(th).siblings().removeClass('active-second')
    $("#dateType").val(type)
    if(type==''){
        // if(){}
        // $('#customInput').css('display','block');
        if($("#customInput").is(":hidden")){
            $('#customInput').show();
        }else{
            $('#customInput').hide();
        }

    }else{
        // $('#customInput').css('display','none');
        $('#customInput').hide();
        $('#startTm').val('');
        $('#endTm').val('');
        $dataInfo.bootstrapTable('refresh');
    }
}

/**
 * 查询参数
 */
function queryParams() {
    var param = {};
    //搜索条件
    param.dateUnit = $("#dateUnit").val();  //上月1 本周2 本月3 本季度4 本年5
    param.companyId=$("#companyId").val()
    return param;
}

/**
 * 查询参数
 */
function queryParamsTable(params) {
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式
    params.companyId=$("#companyId").val()
    params.dateType=$("#dateType").val()
    params.arriveTimeStart=$("#startTm").val()
    params.arriveTimeEnd=$("#endTm").val()
    return params;
}

function timeSelectTable(th,type) {
    $(th).addClass('active-second')
    $(th).siblings().removeClass('active-second')
    $("#dateType").val(type)
    if(type==''){

        if($("#customInput").is(":hidden")){
            $('#customInput').show();
        }else{
            $('#customInput').hide();
        }

    }else{
        $('#customInput').hide();
        $('#startTm').val('');
        $('#endTm').val('');
    }
    refreshTable();
}

/**
 * 上月/本周/本月/本季度/本年切换
 * @param time
 */
function selectTime(time) {
    if (time == 'lastMonth') {//上月
        $('.lastMonth').addClass('active-second');
        $('.week').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.quarterly').removeClass('active-second');
        $('.year').removeClass('active-second');
        $("#dateUnit").val(1);
    }
    if (time == 'week') {//本周
        $('.week').addClass('active-second');
        $('.lastMonth').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.quarterly').removeClass('active-second');
        $('.year').removeClass('active-second');
        $("#dateUnit").val(2);
    }
    if (time == 'month') {//本月
        $('.month').addClass('active-second');
        $('.lastMonth').removeClass('active-second');
        $('.week').removeClass('active-second');
        $('.quarterly').removeClass('active-second');
        $('.year').removeClass('active-second');
        $("#dateUnit").val(3);
    }if (time == 'quarterly') {//本季度
        $('.quarterly').addClass('active-second');
        $('.month').removeClass('active-second');
        $('.lastMonth').removeClass('active-second');
        $('.week').removeClass('active-second');
        $('.year').removeClass('active-second');
        $("#dateUnit").val(4);
    }if (time == 'year') {//本年
        $('.year').addClass('active-second');
        $('.month').removeClass('active-second');
        $('.lastMonth').removeClass('active-second');
        $('.week').removeClass('active-second');
        $('.quarterly').removeClass('active-second');
        $("#dateUnit").val(5);
    }
    refresh();
}

function refreshTable(){
    $dataInfo.bootstrapTable("refreshOptions", { pageNumber: 1 });
}

function refresh(){
    //$dataInfo.bootstrapTable("refreshOptions", { pageNumber: 1 });
    polyLineInitData();//折线图数据初始化
    minutePieInitData();//饼状图数据初始化
}

/**
 * 折线图初始化
 */
function polyLineInit(id,data){
    let dom = document.getElementById(id);
    let myChart = echarts.init(dom);
    const color = ['#caed8b', '#6699ff',"#52cca3"]
    let option = {
        title: {
            text: ''
        },
        tooltip: {
            trigger: 'axis',

            extraCssText: 'font-size:14px;line-height:24px;color:#fff;background:#212947;opacity: 0.9;padding:10px 20px;box-shadow:0 0 3px rgba(0, 0, 0, 0.2)',
            formatter: function(params) {
                let html = `<span style="">${params[0].axisValue}</span>`
                params.forEach(v => {
                    html += `<div>
<span style="display:inline-block;color: #999999;margin-right:5px;border-radius:10px;width:10px;height:10px;border: 2px solid #FFFFFF;background-color:${color[v.componentIndex]};"></span>
${v.seriesName}

<span style="color:${color[v.componentIndex]};font-size:18px;font-weight:700;padding-left: 10px;">${v.value}</span>`
                })
                return html
            }
        },
        legend: {
            top: '20',
            right: '10',
            itemGap: 30,
            data: data.type,
        },
        grid: {
            left: '10',
            right: '10',
            top: '60',
            bottom: '10',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            axisLine: {
                lineStyle: {
                    color: '#ddd'
                }
            },
            axisTick: {
                show: false
            },
            axisLabel: {
                color: '#999999',
                padding: [8, 0, 0, 0]
            },
            // boundaryGap: false,
            data: data.time
        },
        yAxis: {
            type: 'value',
            name: '数量',
            nameGap: 24,
            nameTextStyle: {
                color: '#999999',
                align: 'right'
            },
            minInterval: 1,
            axisLine: {
                lineStyle: {
                    color: '#ddd'
                }
            },
            axisTick: {
                show: false
            },
            axisLabel: {
                color: '#999',
                padding: [0, 8, 0, 0]
            },
            splitLine: {
                show: true,
                lineStyle: {
                    color: '#f3f3f3',
                    type: 'dotted',
                    width: 2
                }
            }
        },
        color: [
            '#5470c6', '#91cc75', '#fac858'
        ],
        series: [
            {
                name: '接听总数',
                type: 'line',
                smooth: true,
                lineStyle: {
                    color: '#caed8b'
                },
                areaStyle: {
                    color: '#caed8b',
                    opacity: 0.8
                },
                itemStyle: {
                    normal: {
                        color: '#caed8b',
                        borderColor: '#caed8b'
                    }
                },
                data: data.sum
            },
            {
                name: '接听',
                type: 'line',
                smooth: true,
                lineStyle: {
                    color: '#3d7fff'
                },
                areaStyle: {
                    color: '#3d7fff',
                    opacity: 0.8
                },
                itemStyle: {
                    normal: {
                        color: '#3d7fff',
                        borderColor: '#3d7fff'
                    }
                },
                data: data.answer
            },
            {
                name: '未接听',
                type: 'line',
                smooth: true,
                lineStyle: {
                    color: '#52cca3'
                },
                areaStyle: {
                    color: '#52cca3',
                    opacity: 0.8
                },
                itemStyle: {
                    normal: {
                        color: '#52cca3',
                        borderColor: '#52cca3'
                    }
                },
                data: data.missed
            },
        ]
    };

    myChart.setOption(option);
    window.addEventListener("resize",function(){
        myChart.resize();
    });
}


/**
 * 饼状图图初始化
 */
function pieInit(id,name,data){
    let dom = document.getElementById(id);
    let myChart = echarts.init(dom);
    let option = {
        tooltip: {
            trigger: 'item'
        },
        legend: {
            top: '5%',
            left: 'center'
        },
        color: [
            '#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452'
        ],
        series: [
            {
                name: name,
                type: 'pie',
                radius: ['40%', '70%'],
                avoidLabelOverlap: false,
                itemStyle: {
                    borderRadius: 10,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                label: {
                    show: false,
                    position: 'center'
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: '40',
                        fontWeight: 'bold'
                    }
                },
                labelLine: {
                    show: false
                },
                data: data
            }
        ]
    };
    myChart.setOption(option);
    window.addEventListener("resize",function(){
        myChart.resize();
    });

}